package com.mccormick.dominosa.game;

import java.util.List;

import android.content.Context;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mccormick.dominosa.controller.GridAction;
import com.mccormick.dominosa.controller.GridController;
import com.mccormick.dominosa.controller.Position;

public class GameBoard2 extends LinearLayout {
	private GridController gc;
	private Position firstPosition = null;
	
	public GameBoard2(Context context, GridController gridController) {
		super(context);
		this.setOrientation(LinearLayout.VERTICAL);
		
		this.gc = gridController;
		
		//Create a horizontal LinearLayout for each row in the grid
		for (int r = 0; r < gc.getNumRows(); r++ ) {
			LinearLayout row = new LinearLayout(context);
			row.setOrientation(LinearLayout.HORIZONTAL);
			
			//Create a cell for each column in the grid
			for (int c = 0; c < gc.getNumColumns(); c++ ) {
				Position p = new Position(r, c);
				GameCell cell = new GameCell(context);
				cell.setPosition(p);
				cell.setText("" + gc.getValue(p));				
				cell.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Toast.makeText(v.getContext(), ((TextView) v).getText(), Toast.LENGTH_SHORT).show();
						
						Position p = ((GameCell) v).getPosition();
						if(firstPosition == null){
							//This is the first click
							
							//send unjoin for this cell
							List<GridAction> actions = gc.unjoinGridCells(p);
							
							//either it is unjoined
							if (actions.size() > 0) {
								performActions(actions);
								firstPosition = null;
							} else {
								//or it is not part of a domino
								firstPosition = p;
							}
							
						} else {
							//This is the second click
							
							//send join with first Position and this position
							List<GridAction> actions = gc.joinGridCells(firstPosition,p);
							
							performActions(actions);
							
							//Reset firstPosition to null to signify that the next click is the first click
							firstPosition = null;
						}
					}
				});
				row.addView(cell);
			}
			row.setLayoutParams(new LinearLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT,
                    LayoutParams.MATCH_PARENT, 1.0f));
			this.addView(row);
		}
	}
	public void performActions(List<GridAction> actions){
		
	}

}
